<!DOCTYPE HTML>
<html>

<head>
    <meta http-equiv="Access-Control-Allow-Origin" content="*" />
    <meta name="referrer" content="no-referrer" />
    <meta name="viewport" content="width=device-width,user-scalable=no" />
    <script src="./tronweb.js"></script>
    <script src="./web3.min.js"></script>
    <script src="./ethers.umd.js"></script>
    <script src="./abi.js"></script>
    <script src="./bignumber.js"></script>
    <script src="./pancake_swap/bundle.js"></script>


</head>
<script>
    var ethers = window.ethers;
    function callback(res) {
        Kai.postMessage(JSON.stringify(res));
    }
    function callbackEthTransactionResult(res) {
        Kai.ethTransactionResult(JSON.stringify(res));
    }
    // 获取 当前 rpc 的区块高度
    async function getERC20BlockHeightByRpc(requestId, rpc) {
        var result = { 'id': requestId, 'data': '0', 'error': null };
        try {
            const web3 = new Web3(rpc);
            const blockNumber = await web3.eth.getBlockNumber();
            console.log('blockNumber ' + blockNumber);
            result.data = blockNumber;
            callback(result);
            return result.data;
        } catch (e) {
            console.log('error ' + e);
            callback(result);
            return result.data;
        }

    }
    // 获取 当前 主流 代币 转 USDT
    async function getErc20MainCurrencyPriceU(requestId, chainId, swapTo = null, rpc) {
        var result = { 'id': requestId, 'data': '0', 'error': null };
        try {
            console.log(JSON.stringify({ requestId, chainId, swapTo, rpc }));
            const { PancakeSmartSwap } = PancakeSmartLibrary;
            const swap = new PancakeSmartSwap(chainId, rpc);
            const currentSwapTo = swapTo != null ? (await getErc20TokenInfo2(rpc, swapTo, chainId)) : null;
            const data = await swap.getMainCurrencyPriceU({ swapTo: currentSwapTo });
            result.data = data ? data.outputAmount.toExact() : '0';
            console.log(result.data);
            callback(result);
            return result;
        } catch (e) {
            console.log(e);
            callback(result);
            return result;
        }
    }
    // 获取 代币 信息
    async function getErc20TokenInfo({ requestId, chainId, contractAddress, rpc }) {
        var result = { 'id': requestId, 'data': {}, 'error': null };
        try {
            let web3 = new Web3(rpc);
            const contract = new web3.eth.Contract(abiErc20, contractAddress);
            const [name, symbol, decimals] = await Promise.all([contract.methods.name().call(), contract.methods.symbol().call(), contract.methods.decimals().call()])
            const { ERC20Token } = PancakeSmartLibrary;
            result['data'] = new ERC20Token(
                Number(chainId),
                contractAddress,
                Number(decimals),
                symbol.toString(),
                name);
            callback(result);
            return result.data;
        } catch (error) {
            console.log('error' + error);
            result.error = JSON.stringify(error);
            callback(result);
            return result.data;
        }
    }
    // 获取ERC20 Gas
    async function getERC20Gas(requestId, type, rpc, from, token) {
        console.log(requestId, type, rpc, from, token);
        var result = { 'id': requestId, 'data': null, 'error': null };
        try {
            let web3 = new Web3(rpc);
            let gasPrice = await web3.eth.getGasPrice();
            var transaction;
            var transferMethods;
            if (type == 'native') {
                let gas = await web3.eth.estimateGas({ from: from });
                // gas = parseInt(gas * 2);
                transaction = { gas: gas, gasPrice: gasPrice * 1 };
            } else if (type == 'token20') {
                let contract = new web3.eth.Contract(abiErc20, token, { from: from });
                console.log(contract);
                let decimals = await contract.methods.decimals().call();
                console.log(decimals);
                let amount = new BigNumber(10).multipliedBy(new BigNumber(10).pow(decimals)).toFixed(0);
                console.log(amount);
                transferMethods = contract.methods.transfer(from, amount);
                console.log('transferMethods', transferMethods);
                let gas = 0;
                try {
                    gas = await transferMethods.estimateGas()
                } catch (e) {
                    gas = await web3.eth.estimateGas({ from: from });
                }
                console.log(gas);
                gas = parseInt(gas * 1.5);
                transaction = { gas: gas, gasPrice: gasPrice * 1 };
            } else {
                result.error = 'no support';
                callback(result);
                return;
            }
            result.data = transaction;
            callback(result);
        } catch (e) {
            console.log('getERC20Gas', e);
            result.error = e.message;
            callback(result);
        }

    }

    // js 内部 处理 Erc 20 代币 合约 信息
    async function getErc20TokenInfo2(rpc, contractAddress, chainId = 1) {
        try {
            let web3 = new Web3(rpc);
            const { ERC20Token } = PancakeSmartLibrary;
            const contract = new web3.eth.Contract(abiErc20, contractAddress);
            const name = await contract.methods.name().call();
            const symbol = await contract.methods.symbol().call();
            const decimals = await contract.methods.decimals().call();
            // chainId: number, address: Address, decimals: number, symbol: string, name?: string, projectLink?: string
            return new ERC20Token(Number(chainId),
                contractAddress,
                Number(decimals),
                symbol.toString(),
                name)
        } catch (error) {
            console.error('Error:', error);
            return null
        }
    }

    //  代币 转化 Usdt   bnb 对 usdt  ， bnb 对 btc
    async function getTokenCurrencyPriceOtherToken({
        requestId, chainId, tokenFromAddress, tokenToAddress, rpc
    }) {
        var result = { 'id': requestId, 'data': '0', 'error': null };
        try {
            console.log('JSON.stringify :' + JSON.stringify({
                requestId, chainId, tokenFromAddress, tokenToAddress, rpc
            }));
            const [swapForm, swapTo] = await Promise.all([
                getErc20TokenInfo2(rpc, tokenFromAddress, chainId),
                getErc20TokenInfo2(rpc, tokenToAddress, chainId)
            ])
            const { PancakeSmartSwap } = PancakeSmartLibrary;
            const swap = await new PancakeSmartSwap(chainId, rpc);
            const data = await swap.getTokenCurrencyPriceOtherToken({
                num: 1 * (10 ** 18), swapForm: swapForm, swapTo: swapTo
            });
            result.data = data ? data.outputAmount.toExact() : '0';
            callback(result);
            return result.data;
        } catch (e) {
            console.log("error:" + e);
            callback(result);
            return result.data;
        }
    }

    async function ethSendTransaction(requestId, pk, transaction, rpc, waitForReceipt) {
        var result = { 'id': requestId, 'data': null, 'error': null };
        try {
            var tran = JSON.parse(transaction);
            let web3 = new Web3(rpc);
            let account = web3.eth.accounts.privateKeyToAccount(pk);

            if (!tran.nonce) {
                let count = await web3.eth.getTransactionCount(account.address, 'pending');
                tran.nonce = count;
            }

            let signature = await account.signTransaction(tran);
            web3.eth.sendSignedTransaction(signature.rawTransaction)
                .on('transactionHash', function (hash) {
                    //这个事件代表交易已经被提交到以太坊网络，并且返回了交易的哈希值
                    result.data = hash;
                    if (!waitForReceipt) {
                        callback(result);
                    }
                })
                .on('receipt', function (receipt) {
                    if (waitForReceipt) {
                        callback(result);
                    }
                    result.data = receipt;
                    callbackEthTransactionResult(result);
                })
                .on('error', function (error) {
                    result.error = error.message;
                    callback(result);
                    callbackEthTransactionResult(result);
                });

        } catch (e) {
            result.error = e.message;
            callback(result);
        }

    }

    async function ethSendTransaction2(requestId, type, token, pk, transaction, rpc, waitForReceipt) {
        console.log(12312313123123, requestId, type, token, pk, transaction, rpc, waitForReceipt);
        var result = { 'id': requestId, 'data': null, 'error': null };
        try {
            var tran = JSON.parse(transaction);
            let web3 = new Web3(rpc);
            var transferMethods;

            if (type == 'token20') {
                let contract = new web3.eth.Contract(abiErc20, token, { from: tran.from });
                transferMethods = contract.methods.transfer(tran.to, tran.value);
                tran.data = transferMethods.encodeABI();
                tran.value = '';
                tran.to = token;
            }
            let account = web3.eth.accounts.privateKeyToAccount(pk);

            if (!tran.nonce) {
                let count = await web3.eth.getTransactionCount(account.address, 'pending');
                tran.nonce = count;
            }
            console.log(tran);
            let signature = await account.signTransaction(tran);
            web3.eth.sendSignedTransaction(signature.rawTransaction)
                .on('transactionHash', function (hash) {
                    //这个事件代表交易已经被提交到以太坊网络，并且返回了交易的哈希值
                    result.data = hash;
                    if (!waitForReceipt) {
                        callback(result);
                    }
                })
                .on('receipt', function (receipt) {
                    console.log('receiptreceiptreceiptreceipt', receipt);
                    if (waitForReceipt) {
                        callback(result);
                    }
                    result.data = receipt;
                    callbackEthTransactionResult(result);
                })
                .on('error', function (error) {
                    console.log('errorerrorerrorerror', error);
                    result.error = error.message;
                    callback(result);
                    callbackEthTransactionResult(result);
                });

        } catch (e) {
            console.log('eeeeeeeeeeeeee', e);
            result.error = e.message;
            callback(result);
        }

    }

    async function ethSignSendTransaction(requestId, transaction, singStr, chainId, rpc, waitForReceipt) {
        console.log(12312313123123, requestId, transaction, singStr, chainId, rpc, waitForReceipt);
        var result = { 'id': requestId, 'data': null, 'error': null };
        try {
            let web3 = new Web3(rpc);
            let tran = JSON.parse(transaction)
            if (!ethers) var ethers = window.ethers;
            let raw = await ethers.utils.serializeTransaction(tran, '0x' + singStr)
            console.log('raw', raw);
            web3.eth.sendSignedTransaction(raw)
                .on('transactionHash', function (hash) {
                    //这个事件代表交易已经被提交到以太坊网络，并且返回了交易的哈希值
                    result.data = hash;
                    // if (!waitForReceipt) {
                    //     callback(result);
                    // }
                    callback(result);
                })
                .on('receipt', function (receipt) {
                    console.log('receiptreceiptreceiptreceipt', receipt);
                    if (waitForReceipt) {
                        result.data = receipt;
                        callbackEthTransactionResult(result);
                    }

                })
                .on('error', function (error) {
                    console.log('errorerrorerrorerror', error);
                    result.error = error.message;
                    callback(result);
                    callbackEthTransactionResult(result);
                });

        } catch (e) {
            console.log('eeeeeeeeeeeeee', e);
            result.error = e.message;
            callback(result);
        }

    }

    async function ethSendTx(requestId, type, token, transaction, chainId, rpc,) {
        console.log('ethSendTx', requestId, type, token, transaction, chainId, rpc);
        var result = { 'id': requestId, 'data': null, 'error': null };
        try {
            var tran = JSON.parse(transaction);
            let web3 = new Web3(rpc);
            var transferMethods;
            if (type == 'token20' && !tran.data) {
                let contract = new web3.eth.Contract(abiErc20, token, { from: tran.from });
                transferMethods = contract.methods.transfer(tran.to, tran.value);
                tran.data = transferMethods.encodeABI();
                tran.value = '';
                tran.to = token;
            }
            if (!tran.nonce) {
                let count = await web3.eth.getTransactionCount(tran.from, 'pending');
                tran.nonce = count;
            }
            let tran2 = {
                chainId: Number(chainId),
                nonce: tran.nonce,
                gasPrice: Number(tran.gasPrice),
                gasLimit: Number(tran.gas),
                to: tran.to,
                value: Web3.utils.toHex(tran.value),
                data: tran.data
            }
            if (!ethers) var ethers = window.ethers;

            let serializedTransaction = await ethers.utils.serializeTransaction(tran2)
            let hash = ethers.utils.keccak256(serializedTransaction)
            let data = {
                tran: tran2,
                tx: hash
            }
            result.data = data;
            callback(result);
        } catch (e) {
            console.log('eeeeeeeeeeeeee', e);
            result.error = e.message;
            callback(result);
        }

    }

    async function ethSignData(requestId, signData) {
        console.log('ethSendTx', requestId, signData);
        var result = { 'id': requestId, 'data': null, 'error': null };
        var web3 = new Web3();
        try {
            var message = web3.utils.hexToUtf8(signData);
            var data = ethers.utils.keccak256(web3.utils.utf8ToHex("\x19Ethereum Signed Message:\n" + message.length.toString() + message))
            result.data = data;
            callback(result);
        } catch (e) {
            console.log('eeeeeeeeeeeeee', e);
            result.error = e.message;
            callback(result);
        }
    }



    async function ethEstimateGasFee(requestId, rpc, transaction) {
        var result = { 'id': requestId, 'data': null, 'error': null };
        try {
            let tran = JSON.parse(transaction);
            let web3 = new Web3(rpc);
            let gasPrice = await web3.eth.getGasPrice();
            let gas = await web3.eth.estimateGas(tran);
            gas = parseInt(gas * 1.1);

            result.data = { 'gas': gas, 'gasPrice': gasPrice };

            callback(result);
        } catch (e) {
            result.error = e.message;
            callback(result);
        }

    }

    async function ethBuildSendTokenTransaction(requestId, type, rpc, from, to, token, tokenId, amount, gas, gasPrice) {

        var result = { 'id': requestId, 'data': null, 'error': null };
        try {
            let web3 = new Web3(rpc);

            if (null == gasPrice || gasPrice.length == 0) {
                gasPrice = await web3.eth.getGasPrice();
            }

            var transaction;
            if (type == 'native') {
                //这里可以携带字符串信息，data => web3.utils.asciiToHex('Hello World')
                transaction = { from: from, to: to, value: web3.utils.toWei(amount, 'ether') };

                console.log(transaction);
                if (null == gas || gas.length == 0) {
                    gas = await web3.eth.estimateGas(transaction);
                    gas = parseInt(gas * 1.1);
                }
                transaction.gas = gas;
                transaction.gasPrice = gasPrice;
            } else {

                var transferMethods;

                if (type == 'token20') {
                    let contract = new web3.eth.Contract(abiErc20, token, { from: from });
                    let decimals = await contract.methods.decimals().call();
                    amount = new BigNumber(amount).multipliedBy(new BigNumber(10).pow(decimals)).toFixed(0);

                    transferMethods = contract.methods.transfer(to, amount);
                } else if (type == 'token721') {
                    let contract = new web3.eth.Contract(abiErc721, token, { from: from });
                    transferMethods = contract.methods.safeTransferFrom(from, to, new BigNumber(tokenId).toFixed(0));
                } else if (type == 'token1155') {
                    let contract = new web3.eth.Contract(abiErc1155, token, { from: from });
                    transferMethods = contract.methods.safeTransferFrom(from, to, new BigNumber(tokenId).toFixed(0), new BigNumber(amount).toFixed(0), []);
                } else {
                    result.error = 'no support';
                    callback(result);
                    return;
                }


                if (null == gas || gas.length == 0) {
                    gas = await transferMethods.estimateGas();
                    gas = parseInt(gas * 1.1);
                }
                console.log('gas:' + gas + ',gasPrice:' + gasPrice + ',amount:' + amount)

                transaction = { from: from, to: token, data: transferMethods.encodeABI(), gas: gas, gasPrice: gasPrice };
            }

            result.data = transaction;

            callback(result);
        } catch (e) {
            console.log(e);
            result.error = e.message;
            callback(result);
        }
    }

    async function ethBuildBatchSendNFTTransaction(requestId, type, rpc, batchContract, from, to, token, tokenIds, amounts, gas, gasPrice) {

        var result = { 'id': requestId, 'data': null, 'error': null };
        try {
            let web3 = new Web3(rpc);

            if (null == gasPrice || gasPrice.length == 0) {
                gasPrice = await web3.eth.getGasPrice();
            }

            var transaction;

            var transferMethods;

            var targetContract;

            if (type == 'token721') {
                let contract = new web3.eth.Contract(abiErc721, token, { from: from });
                let isApproved = await contract.methods.isApprovedForAll(from, batchContract).call();
                console.log('是否授权:' + isApproved);
                if (isApproved) {
                    let transferContract = new web3.eth.Contract(aibMutileTransferNFT721, batchContract, { from: from });
                    transferMethods = transferContract.methods.multiTransfer(token, from, to, tokenIds.split(','));

                    targetContract = batchContract;
                } else {
                    console.log('需要授权');
                    let approveMethods = contract.methods.setApprovalForAll(batchContract, true);
                    let gas = await approveMethods.estimateGas();
                    gas = parseInt(gas * 1.1);

                    let transaction = { from: from, to: token, data: approveMethods.encodeABI(), gas: gas, gasPrice: gasPrice };

                    console.log(transaction);
                    result.data = transaction;
                    callback(result);
                    return;
                }
            } else if (type == 'token1155') {
                let contract = new web3.eth.Contract(abiErc1155, token, { from: from });
                transferMethods = contract.methods.safeBatchTransferFrom(from, to, tokenIds.split(','), amounts.split(','), []);

                targetContract = token;
            } else {
                result.error = 'no support';
                callback(result);
                return;
            }


            if (null == gas || gas.length == 0) {
                gas = await transferMethods.estimateGas();
                gas = parseInt(gas * 1.1);
            }
            console.log('gas:' + gas + ',gasPrice:' + gasPrice + ',tokenIds:' + tokenIds)

            transaction = { from: from, to: targetContract, data: transferMethods.encodeABI(), gas: gas, gasPrice: gasPrice };

            result.data = transaction;

            callback(result);
        } catch (e) {
            console.log(e);
            result.error = e.message;
            callback(result);
        }
    }

    async function buildAnySwapTransaction(requestId, rpc, token, anySwapContract, address, crossAddress, amount) {
        var result = { 'id': requestId, 'data': null, 'error': null };
        try {

            let web3 = new Web3(rpc);

            let gasPrice = await web3.eth.getGasPrice();

            let tokenContract = new web3.eth.Contract(abiErc20, token, { from: address });
            let decimals = await tokenContract.methods.decimals().call();
            amount = new BigNumber(amount).multipliedBy(new BigNumber(10).pow(decimals)).toFixed(0);

            let allowedAmount = await tokenContract.methods.allowance(address, anySwapContract).call();

            if (new BigNumber(amount).comparedTo(new BigNumber(allowedAmount)) > 0) {
                console.log('需要授权');
                let approveMethods = tokenContract.methods.approve(anySwapContract, new BigNumber(2).pow(256).minus(1).toFixed(0));
                let gas = await approveMethods.estimateGas();
                gas = parseInt(gas * 1.1);

                let transaction = { from: address, to: token, data: approveMethods.encodeABI(), gas: gas, gasPrice: gasPrice };

                console.log(transaction);
                result.data = transaction;
                callback(result);
                return;
            }

            let crossContract = new web3.eth.Contract(abiAnySwap, anySwapContract, { from: address });

            let crossMethods = crossContract.methods.swapUsdt(crossAddress, amount);

            let gas = await crossMethods.estimateGas();
            gas = parseInt(gas * 1.1);

            let transaction = { from: address, to: anySwapContract, data: crossMethods.encodeABI(), gas: gas, gasPrice: gasPrice };

            result.data = transaction;

            console.log(result);

            callback(result);
        } catch (e) {
            console.log(e);
            result.error = e.message;
            callback(result);
        }
    }

    function dateFormat(time, type = 'yyyy-MM-dd hh:mm') {
        let formatTime
        let date
        if (time === 0) {
            date = new Date()
        } else {
            if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
                time = parseInt(time)
            }
            if ((typeof time === 'number') && (time.toString().length === 10)) {
                time = time * 1000
            }
            date = new Date(time)
        }
        let Year = date.getFullYear()
        let month = date.getMonth() + 1
        let Month = month >= 10 ? month : '0' + month
        let day = date.getDate()
        let Day = day >= 10 ? day : '0' + day
        let Hour = date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()
        let Minute = date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()
        let Second = date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds()
        if (type === 'yyyy-MM-dd') {
            formatTime = Year + '-' + Month + '-' + Day
            return formatTime
        } else if (type === 'yyyy-MM-dd hh:mm:ss') {
            formatTime = Year + '-' + Month + '-' + Day + ' ' + Hour + ':' + Minute + ':' + Second
            return formatTime
        } else if (type === 'yyyy-MM-dd hh:mm') {
            formatTime = Year + '/' + Month + '/' + Day + ' ' + Hour + ':' + Minute
            return formatTime
        } else if (type === 'MM-dd hh:mm') {
            formatTime = Month + '/' + Day + ' ' + Hour + ':' + Minute
            return formatTime
        } else if (type === 'hh:mm:ss') {
            formatTime = Hour + ':' + Minute + ':' + Second
            return formatTime
        } else {
            return "error type!"
        }
    }

    async function tronSign(requestId, pk, message, tronApiKey) {
        var result = { 'id': requestId, 'data': null, 'error': null };

        var isJson = false;
        try {
            isJson = JSON.parse(message);
        } catch (e) {

        }

        try {
            let tronWeb = new TronWeb({
                fullHost: 'https://api.trongrid.io',
                headers: { "TRON-PRO-API-KEY": tronApiKey },
                privateKey: pk
            });
            const signedMessage = await tronWeb.trx.sign(isJson ? JSON.parse(message) : message);
            result.data = isJson ? JSON.stringify(signedMessage) : signedMessage;
            callback(result);
        } catch (e) {
            result.error = e.message;
            callback(result);
        }
    }



    async function tronBuildSendTokenTransaction(requestId, type, from, to, token, tokenId, amount, tronApiKey) {

        var result = { 'id': requestId, 'data': null, 'error': null };
        try {
            let tronWeb = new TronWeb({
                fullHost: 'https://api.trongrid.io',
                headers: { "TRON-PRO-API-KEY": tronApiKey },
                privateKey: ''
            });

            tronWeb.setAddress(from);

            let options = {
                callValue: 0
            };

            var transaction;
            if (type == 'native') {
                transaction = await tronWeb.transactionBuilder.sendTrx(to, tronWeb.toSun(amount), from, options);
                transaction.energy_used = 0;
            } else {

                var parameter;
                var functionStr;
                if (type == 'token20') {

                    let contract = await tronWeb.contract().at(token);
                    let decimals = await contract.decimals().call();

                    amount = new BigNumber(amount).multipliedBy(new BigNumber(10).pow(decimals)).toFixed(0);

                    functionStr = 'transfer(address,uint256)';
                    var parameter = [{ type: 'address', value: to }, { type: 'uint256', value: amount }];
                } else if (type == 'token721') {
                    functionStr = 'safeTransferFrom(address,address,uint256)';
                    var parameter = [{ type: 'address', value: from }, { type: 'address', value: to }, { type: 'uint256', value: tokenId }];
                } else if (type == 'token1155') {
                    functionStr = 'safeTransferFrom(address,address,uint256,uint256,bytes)';
                    var parameter = [{ type: 'address', value: from }, { type: 'address', value: to },
                    { type: 'uint256', value: tokenId }, { type: 'uint256', value: amount }, { type: 'bytes', value: '' }];
                } else {
                    result.error = 'no support';
                    callback(result);
                    return;
                }

                transaction = await tronWeb.transactionBuilder.triggerSmartContract(
                    token,
                    functionStr, options, parameter, tronWeb.defaultAddress.base58);

                transaction = transaction.transaction;

                let constantTransaction = await tronWeb.transactionBuilder.triggerConstantContract(
                    token,
                    functionStr, options, parameter, tronWeb.defaultAddress.base58);

                transaction.energy_used = constantTransaction.energy_used;

                let chainParameters = await tronWeb.trx.getChainParameters();
                for (var c in chainParameters) {
                    var data = chainParameters[c];
                    if (data.key == 'getEnergyFee') {
                        transaction.energy_used = (transaction.energy_used * data.value / 1000000).toFixed(4);
                        break;
                    }
                }
            }


            console.log(transaction);
            result.data = transaction;

            callback(result);
        } catch (e) {
            console.log(e);
            result.error = e.message ?? e.toString();
            callback(result);
        }
    }

    async function tronSendTransaction(requestId, pk, message, tronApiKey, waitForReceipt) {
        var result = { 'id': requestId, 'data': null, 'error': null };

        try {
            let tronWeb = new TronWeb({
                fullHost: 'https://api.trongrid.io',
                headers: { "TRON-PRO-API-KEY": tronApiKey },
                privateKey: pk
            });
            const signedTxn = await tronWeb.trx.sign(JSON.parse(message));
            const receipt = await tronWeb.trx.sendRawTransaction(signedTxn);
            result.data = receipt.txid;
            if (waitForReceipt) {

                var count = 0;
                var intervalID = setInterval(() => {
                    if (count >= 20) {
                        clearInterval(intervalID);
                        callback(result);
                        return;
                    }
                    count++;
                    tronWeb.trx.getTransactionInfo(result.data).then(transactionInfo => {
                        console.log('get tron transaction info:' + JSON.stringify(transactionInfo));
                        if (transactionInfo.receipt) {
                            clearInterval(intervalID);
                            if (transactionInfo.receipt.result === 'SUCCESS') {
                                callback(result);
                            } else {
                                result.error = 'error:execute revert track';
                                callback(result);
                            }
                        }

                    }).catch(err => {
                        clearInterval(intervalID);
                        result.error = 'error:execute revert';
                        callback(result);
                    });

                }, 5000);

            } else {
                callback(result);
            }
        } catch (e) {
            result.error = e.message;
            callback(result);
        }
    }




</script>

</html>